package org.thirdHero.wx.service;

import org.thirdHero.core.util.HttpRequest;
import org.thirdHero.db.domain.LitemallUser;
import org.thirdHero.db.service.LitemallUserService;
import org.thirdHero.wx.dao.UserInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.thirdHero.wx.domain.WxUserOpenId;
import org.thirdHero.core.util.JsonUtils;

import javax.annotation.Resource;

@Service
public class UserInfoService {
    @Resource
    private LitemallUserService userService;


    public UserInfo getInfo(Integer userId) {
        LitemallUser user = userService.findById(userId);
        Assert.state(user != null, "用户不存在");
        UserInfo userInfo = new UserInfo();
        userInfo.setNickName(user.getNickname());
        userInfo.setAvatarUrl(user.getAvatar());
        return userInfo;
    }

    public WxUserOpenId  getWxUserOpenId(String appId, String appSecret, String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String param = "appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";

        String res = HttpRequest.sendGet(url, param);
        WxUserOpenId wxUserOpenId = JsonUtils.readValue(res, WxUserOpenId.class);
        return wxUserOpenId;
    }

}
